<template>
  <div class="art-full-height">
    <!-- 主列表：字典类型 -->
    <DictTypeSearch v-show="showSearchBar" v-model="typeSearchForm" @search="handleTypeSearch"
      @reset="handleTypeReset" />
    <ElCard class="art-table-card" shadow="never" :style="{ 'margin-top': showSearchBar ? '12px' : '0' }">

      <ArtTableHeader v-model:show-search-bar="showSearchBar" v-model:columns="typeColumnChecks" :loading="typeLoading"
        @refresh="typeRefresh">
        <template #left>
          <ElSpace wrap>
            <ElButton v-auth="'add'" type="primary" @click="showTypeDialog('add')" v-ripple>新增类型</ElButton>
          </ElSpace>
        </template>
      </ArtTableHeader>

      <ArtTable rowKey="id" :loading="typeLoading" :data="typeData" :columns="typeColumns" :pagination="typePagination"
        @pagination:size-change="handleTypeSizeChange" @pagination:current-change="handleTypeCurrentChange" />
    </ElCard>

    <!-- 右侧抽屉：字典项列表 -->
    <ElDrawer v-model="itemDrawerVisible" direction="rtl" :with-header="false" size="55%">
      <div class="drawer-content">
        <div class="drawer-header">
          <div class="header-left">
            <b>字典项管理</b>
            <span v-if="selectedTypeCode" class="sub">当前类型：{{ selectedTypeName }}（{{ selectedTypeCode }}）</span>
          </div>
          <div class="header-actions">
            <ElButton type="primary" :disabled="!selectedTypeCode" v-auth="'add'" @click="showItemDialog('add')"
              v-ripple>
              新增字典项
            </ElButton>
          </div>
        </div>

        <ArtTable rowKey="id" :loading="itemLoading" :data="itemData" :columns="itemColumns" :showTableHeader="false"
          size="small" />
      </div>
    </ElDrawer>

    <!-- 弹窗：字典类型 -->
    <DictTypeDialog v-model:visible="typeDialogVisible" :type="typeDialogType" :editData="currentTypeData"
      @submit="handleTypeDialogSubmit" />

    <!-- 弹窗：字典项 -->
    <DictItemDialog v-model:visible="itemDialogVisible" :type="itemDialogType" :editData="currentItemData"
      :dictTypeCode="selectedTypeCode" @submit="handleItemDialogSubmit" />
  </div>
</template>

<script setup lang="ts">
import ArtButtonTable from '@/components/core/forms/art-button-table/index.vue'
import { useTable } from '@/composables/useTable'
import { fetchDictTypeList, deleteDictType, type DictTypeResponse, type DictTypeQuery } from '@/api/system/dict'
import { fetchDictItemList, deleteDictItem, type DictItemResponse } from '@/api/system/dict_item'
import DictTypeSearch from '@/views/system/dict/modules/dict-type-search.vue'
import DictTypeDialog from '@/views/system/dict/modules/dict-type-dialog.vue'
import DictItemDialog from '@/views/system/dict/modules/dict-item-dialog.vue'

defineOptions({ name: 'DictManage' })

const showSearchBar = ref(false)

// 左侧：字典类型搜索表单
const typeSearchForm = ref<DictTypeQuery>({
  type_code: undefined,
  type_name: undefined,
  keyword: undefined
})

// 当前选中的字典类型
const selectedTypeCode = ref<string>('')
const selectedTypeName = ref<string>('')

// 类型列表 useTable
const {
  data: typeData,
  columns: typeColumns,
  columnChecks: typeColumnChecks,
  loading: typeLoading,
  pagination: typePagination,
  refreshData: typeRefresh,
  handleSizeChange: handleTypeSizeChange,
  handleCurrentChange: handleTypeCurrentChange,
  searchParams: typeSearchParams,
  getData: getTypeData
} = useTable({
  core: {
    apiFn: fetchDictTypeList,
    apiParams: {
      current: 1,
      size: 20,
      ...typeSearchForm.value
    },
    immediate: false, // 禁用自动加载，避免与onMounted重复请求
    columnsFactory: () => [
      { prop: 'id', label: 'ID', width: 80, checked: false },
      { prop: 'type_code', label: '类型编码', width: 160 },
      { prop: 'type_name', label: '类型名称' },
      { prop: 'type_desc', label: '描述' },
      { prop: 'create_time', label: '创建时间' },
      { prop: 'update_time', label: '更新时间' },
      {
        prop: 'operation',
        label: '操作',
        width: 165,
        aglin: 'right',
        formatter: (row: DictTypeResponse) =>
          h('div', [
            h(ArtButtonTable, {
              type: 'view',
              onClick: () => handleTypeRowClick(row)
            }),
            h(ArtButtonTable, {
              type: 'edit',
              onClick: () => showTypeDialog('edit', row)
            }),
            h(ArtButtonTable, {
              type: 'delete',
              onClick: () => handleDeleteType(row)
            })
          ])
      }
    ]
  }
})

// 字典项列表 useTable（依赖 selectedTypeCode，展示在抽屉内）
const {
  data: itemData,
  columns: itemColumns,
  loading: itemLoading,
  refreshData: itemRefresh,
  searchParams: itemSearchParams,
  getData: getItemData
} = useTable({
  core: {
    apiFn: fetchDictItemList,
    apiParams: {
      current: 1,
      size: 20
    },
    immediate: false, // 禁用自动加载，只在选择字典类型时手动加载
    columnsFactory: () => [
      { prop: 'id', label: 'ID', width: 80, checked: false },
      { prop: 'dict_key', label: '键' },
      { prop: 'dict_value', label: '值', minWidth: 220 },
      { prop: 'category', label: '分类', width: 80 },
      { prop: 'score', label: '评分', width: 80 },
      { prop: 'options', label: '选项', checked: false },
      { prop: 'sort_order', label: '排序', width: 80 },
      { prop: 'create_time', label: '创建时间', checked: false },
      { prop: 'update_time', label: '更新时间', checked: false },
      {
        prop: 'operation',
        label: '操作',
        width: 120,
        aglin: 'right',
        formatter: (row: DictItemResponse) =>
          h('div', [
            h(ArtButtonTable, {
              type: 'edit',
              onClick: () => showItemDialog('edit', row)
            }),
            h(ArtButtonTable, {
              type: 'delete',
              onClick: () => handleDeleteItem(row)
            })
          ])
      }
    ]
  }
})

// 点击类型打开右侧抽屉并载入字典项
const itemDrawerVisible = ref(false)
const handleTypeRowClick = (row: DictTypeResponse) => {
  selectedTypeCode.value = row.type_code
  selectedTypeName.value = row.type_name
  // 更新字典项搜索参数并重新获取数据
  itemSearchParams.dict_type = row.type_code
  itemSearchParams.current = 1
  itemDrawerVisible.value = true
  getItemData()
}

// 类型搜索与重置
const handleTypeSearch = (params: Record<string, any>) => {
  const keys = ['type_code', 'type_name', 'keyword']
  const sp = typeSearchParams as Record<string, any>
  keys.forEach((k) => {
    sp[k] = params[k] ?? undefined
  })
  typeSearchParams.current = 1
  getTypeData()
}
const handleTypeReset = () => {
  const keys = ['type_code', 'type_name', 'keyword']
  const sp = typeSearchParams as Record<string, any>
  keys.forEach((k) => delete sp[k])
  typeSearchParams.current = 1
  getTypeData()
}

// 抽屉内不提供查询栏，分页与刷新由 useTable 管理

// 弹窗：类型
const typeDialogVisible = ref(false)
const typeDialogType = ref<'add' | 'edit'>('add')
const currentTypeData = ref<Partial<DictTypeResponse>>({})
const showTypeDialog = (type: 'add' | 'edit', row?: DictTypeResponse) => {
  typeDialogType.value = type
  currentTypeData.value = row || {}
  nextTick(() => {
    typeDialogVisible.value = true
  })
}
const handleTypeDialogSubmit = async () => {
  typeDialogVisible.value = false
  currentTypeData.value = {}
  typeRefresh()
}

// 弹窗：字典项
const itemDialogVisible = ref(false)
const itemDialogType = ref<'add' | 'edit'>('add')
const currentItemData = ref<Partial<DictItemResponse>>({})
const showItemDialog = (type: 'add' | 'edit', row?: DictItemResponse) => {
  if (!selectedTypeCode.value) {
    ElMessage.warning('请先选择字典类型')
    return
  }
  itemDialogType.value = type
  currentItemData.value = row || {}
  nextTick(() => {
    itemDialogVisible.value = true
  })
}
const handleItemDialogSubmit = async () => {
  itemDialogVisible.value = false
  currentItemData.value = {}
  itemRefresh()
}

// 删除：类型
const handleDeleteType = async (row: DictTypeResponse) => {
  try {
    await ElMessageBox.confirm(`确定要删除该字典类型吗？`, '删除字典类型', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    const id = Number(row?.id)
    if (!id) {
      ElMessage.error('缺少类型ID，无法删除')
      return
    }
    await deleteDictType(id)
    ElMessage.success('删除成功')
    typeRefresh()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败，请稍后重试')
    }
  }
}

// 删除：字典项
const handleDeleteItem = async (row: DictItemResponse) => {
  try {
    await ElMessageBox.confirm(`确定要删除该字典项吗？`, '删除字典项', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    const id = Number(row?.id)
    if (!id) {
      ElMessage.error('缺少字典项ID，无法删除')
      return
    }
    await deleteDictItem(id)
    ElMessage.success('删除成功')
    itemRefresh()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败，请稍后重试')
    }
  }
}

// 初次加载类型列表，并默认选中第一项联动右侧
onMounted(async () => {
  await getTypeData()
})
</script>

<style lang="scss" scoped>
.art-table-card {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.drawer-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
  height: 100%;
}

.drawer-header {
  display: flex;
  gap: 8px;
  align-items: baseline;
  margin-bottom: 8px;
  justify-content: space-between;

  .header-left {
    display: flex;
    gap: 8px;
    align-items: baseline;
  }

  .header-actions {
    display: flex;
    align-items: center;
  }

  .sub {
    color: var(--el-text-color-secondary);
    font-size: 13px;
  }
}
</style>
<style lang="scss">
/* 取消抽屉内部滚动限制 */
.el-drawer__body {
  display: flex;
  flex-direction: column;
}

.el-drawer__body .drawer-content {
  flex: 1;
}
</style>
